import os
import pathlib
import re
from pathlib import Path

import cv2

from cjc.project_setting import fourcc, media_ext


# fps, w, h = 30, im0.shape[1], im0.shape[0]


def increment_path(path, exist_ok=False, sep='', mkdir=False):
    # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
    path = Path(path)  # os-agnostic
    stem = path.stem
    folder = str(path.parent)
    suffix = path.suffix
    if path.exists() and not exist_ok:
        # print("stem:",stem)
        match_obj = re.split(r'(\d+$)', stem, re.M | re.I)
        # print("match_obj", match_obj)
        if len(match_obj) == 1:
            start = 1
        elif len(match_obj) > 1:
            start = int(match_obj[1])
        stem = match_obj[0]
        for n in range(start, 9999):
            p = f'{folder}/{stem}{sep}{n}{suffix}'  # increment path
            if not os.path.exists(p):  #
                break
        path = Path(p)

    if mkdir:
        path.mkdir(parents=True, exist_ok=True)  # make directory

    return path
# ['webcam.mp', '41', '']
# ['webcam.mp42.mp', '41', '']



#
# class Cv2Mp4Saver:
#
#     def __init__(self, vid_cap, save_path=None):  #:VideoCapture
#         self.save_path = save_path
#         self.fps = None
#         self.w = 0
#         self.h = 0
#         self.vid_writer = None
#
#     # fps, w, h = 30, im0.shape[1], im0.shape[0]
#
#     def set_vid_cap(self, vid_cap):
#         self.fps = vid_cap.get(cv2.CAP_PROP_FPS)
#         self.w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
#         self.h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
#         self.vid_writer = cv2.VideoWriter(self.save_path, cv2.VideoWriter_fourcc(*fourcc), self.fps, (self.w, self.h))
#
#     def refresh_path(self):
#         self.save_path = increment_path(self.save_path)
#         print(self.save_path)
#         self.vid_writer = cv2.VideoWriter(self.save_path, cv2.VideoWriter_fourcc(*fourcc), self.fps, (self.w, self.h))
#
#     def write(self, img):
#         """
#         Parameters
#         ----------
#         img  图片
#
#         Returns
#         -------
#         """
#         if self.vid_writer is not None:
#             self.vid_writer.write(img)


class Cv2StreamSaver:

    def __init__(self, vid_cap, save_path=None):  #:VideoCapture
        self.none_path = self.create_none_path(save_path)
        self.save_path = str(save_path) #保存视频文件
        self.fps = 30
        self.w = 0
        self.h = 0
        self.vid_writer = None
        self.save_path_refreshed = False  # 刷新后
        self.duration = 0
        self.min_duration = 300  # 小于300帧的视频会被重写

    # fps, w, h = 30, im0.shape[1], im0.shape[0]

    def refresh_writer(self):
        # cv2.VideoWriter_fourcc(*'mp4v')
        self.vid_writer = cv2.VideoWriter(self.save_path, cv2.VideoWriter_fourcc(*fourcc), self.fps,
                                          (self.w, self.h))
        self.duration = 0

    def set_writer_none(self):
        self.vid_writer = cv2.VideoWriter(self.none_path, cv2.VideoWriter_fourcc(*fourcc), self.fps,
                                          (self.w, self.h))
        self.duration = 0

    @staticmethod
    def create_none_path(_p):
        return f'{pathlib.Path(_p).parent}/none_path'+media_ext

    def refresh_path(self):
        if not self.save_path_refreshed:
            # if self.duration > self.min_duration:
            self.save_path = str(increment_path(self.save_path))
            self.save_path_refreshed = True
            self.set_writer_none()

    def write(self, im0):
        if im0 is None:
            return
        if self.w == 0 and self.h == 0:
            self.fps, self.w, self.h = 30, im0.shape[1], im0.shape[0]
            self.refresh_path()
            self.refresh_writer()
        if self.vid_writer is not None:
            if self.save_path_refreshed:  # 更新一下writer
                self.refresh_writer()
            try:
                self.vid_writer.write(im0)
            except Exception as e:
                print("写入出错",e)
            self.save_path_refreshed = False
            self.duration += 1

if __name__ == '__main__':
    css =Cv2StreamSaver(None,"runs/track/webcam.mp4")
    css.refresh_path()
    print(css.save_path)